package com.ys.fmms.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ys.fmms.util.JwtHelper;
import com.ys.fmms.util.Result;
import com.ys.fmms.util.ResultCodeEnum;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HandlerRequestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ///因为是在请求头中发送token，所以第一次请求的方法为"OPTIONS"，具体可以看TCP/IP协议
        String method = request.getMethod();
        if("OPTIONS".equalsIgnoreCase(method)){
            return true;
        }
        String token = request.getHeader("token");
        // 判断有没有token
        if ( !StringUtils.hasText(token)) {
            Result result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
            handlerResponseResult(result, response);
        }
        // 判断token是否失效 false没失效 true失效
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration) {
                Result result = Result.build(null, ResultCodeEnum.TOKEN_ERROR);
                handlerResponseResult(result, response);
        }
        return true;
    }

    private void handlerResponseResult(Result result, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            // 必须设置响应头
            response.setContentType("application/json;charset=utf-8");
            out = response.getWriter();
            // 调用jackson工具将result转为json格式对象
            String s = new ObjectMapper().writeValueAsString(result);
            out.print(s);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
